package cn.zcscloud.mall.interceptor;

import cn.zcscloud.mall.mbg.model.UmsAdmin;
import cn.zcscloud.mall.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * ClassName: TokenInterceptor
 * Description:
 * date: 2022/3/31 17:10
 *
 * @author zjf95
 * @since JDK 1.8
 */

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.err.println(new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss").format(new Date()) + "访问：url ==> " + request.getMethod() + request.getRequestURI());
        //添加这行代码，让OPTIONS请求通过
        String token = request.getHeader("Authorization");

        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        //1. 获取请求头里面的token

        System.out.println("获取的token为：" + token);
        try {
            token = token.split(" ")[1];
        } catch (Exception e) {
            token = null;
        }
        System.out.println("解析后的token为：" + token);
        //2. 判断所获得的token是否合理
        boolean verifyToken = JwtUtils.verifyToken(token);

        //3. 如果获得的token不合理，则返回401
        if (!verifyToken) {
            response.setStatus(401);
            return false;
        }
        //4. 如果合理，则放行

        //将token中的数据存储到Threadlocal中
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        String username = (String) claims.get("username");

        UmsAdmin user = new UmsAdmin();
        user.setId(Long.valueOf(userId));
        user.setUsername(username);

        // UserHolder.set(user);
        UserHolder.set(user);
        System.out.println(request.getMethod() + request.getRequestURI()+"请求放行");
        return true;
    }
}
